/**
 *****************************************************************************
 * DESC ：聊天程序客户端. 
 * Author : Junwei Zhang 
 * CREATEDATE ：2012-6-3 
 * MODIFYLIST ：       	Name 			 Date 			Reason/Contents
 * 				------------------------------------------------------ 
 * 				 	Junwei Zhang     2012-6-3		Created.
 ****************************************************************************
 **/
package com.me.client;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.ListCellRenderer;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.BevelBorder;

import com.me.client.JTalkClient.MemberData;

/**
 * 
 * <br/>
 * 下午2:08:00 2012-6-3
 * 
 * @Author <a href="mailto:mestudying@sina.com">Junwei Zhang</a><br/>
 **/
public class JTalkClientFront extends JFrame implements ActionListener, JTalkClientCommandInterface {

	private static final long serialVersionUID = 1L;

	private ClassLoader classLoader = null;
	/** 链接服务器状态 */
	public boolean isConnected = false;

	private JMenuBar jMenuBarMain = null;
	private JMenu jMenuFile = null;
	private JMenuItem jMenuItemSettings = null;
	private JMenuItem jMenuItemExit = null;
	private JMenu jMenuServer = null;
	private JMenuItem jMenuItemCreateAccount = null;
	private JMenuItem jMenuItemCommand = null;
	private JMenuItem jMenuItemCreateChatRoom = null;
	private JMenuItem jMenuItemConnect = null;
	private JMenu jMenuStatus = null;
	private JCheckBoxMenuItem jMenuItemStatus = null;
	private JMenu jMenuPlugins = null;
	private JMenu jMenuHelp = null;
	private JMenuItem jMenuItemAbout = null;

	private JPanel jPanelTool = null;
	private JToolBar jToolBar = null;
	private JButton jButtonConnect = null;
	private JToggleButton jToggleButtonStatus = null;
	private JButton jButtonConfig = null;

	private JPanel jPanelStatus = null;
	private JLabel jLabelStatusVersion = null;
	private JLabel jLabelStatusConnect = null;

	private JPanel jPanelToolBarSide = null;
	private JToolBar jToolBarSide = null;
	private JButton jButtonOpenChat = null;
	private JButton jButtonSendMail = null;

	private JPanel jPanelMemberList = null;
	private JScrollPane jScrollPaneMembers = null;
	private JList jListMembers = null;

	public JTalkClient theClient = null;
	/** 右击弹出菜单. */
	private JTalkFrontPopup userPopup = null;
	/** 命令面板. */
	private JTalkFrontCommand myCommandDialog = null;
	/** 设置面板. */
	private JTalkFrontSettings mySettings = null;
	/** 插件显示面板. */
	public JTalkClientPluginsInfo myPluginsInfo = null;
	/** 插件加载器. */
	private JTalkPlugInLoader myPluginsLoader = null;
	/** 插件快捷方式面板. */
	private JPanel jPanelPlugins = null;
	/** 消息提示框. */
	private NotificationWindow newMessageNotificator = null;

	public JTalkClientFront(JTalkClient client) {
		if (client == null) {
			this.theClient = new JTalkClient();
		} else {
			this.theClient = client;
		}
		this.classLoader = JTalkClientFront.class.getClassLoader();
		/** -----------------------初始化菜单------------------------- */
		this.initMenu();
		/** -------------------------初始化工具栏----------------------------- */
		this.initToolBar();
		/** -------------------------初始化底部状态栏----------------------------- */
		this.initBottomStatus();
		/** -------------------------初始化侧面菜单栏----------------------------- */
		this.initToolBarSide();
		/** -------------------------初始化中间聊天列表----------------------------- */
		this.initPaneMemberList();

		/** -------------------------初始化此JFrame属性----------------------------- */
		this.initSelf();

		UpdateTimer updateTimer = new UpdateTimer(this);
		updateTimer.start();

		if (this.loadAllPlugins()) {
			this.updatePluginShortcuts();
		}
		this.theClient.setFrontend(this);
	}

	/**
	 * 加载插件的快捷方式.
	 */
	public void updatePluginShortcuts() {
		String[] embededPlugins = this.theClient.getPluginShortcuts();
		JTalkClientPlugInInterface plugin = null;
		this.jPanelPlugins.removeAll();
		for (String s : embededPlugins) {
			plugin = this.myPluginsLoader.getPluginByName(s);
			if (plugin != null) {
				JButton button = new JButton();
				button.setName(plugin.getClass().getName());
				button.setToolTipText("Plugin: " + plugin.getName());
				button.setMargin(new Insets(2, 2, 2, 2));
				button.setPreferredSize(new Dimension(48, 32));
				if (plugin.getIcon() == null) {
					button.setText(plugin.getName());
				} else {
					button.setIcon(plugin.getIcon());
				}
				button.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						openPluginMainGUIFor(((JButton) e.getSource()).getName());
					}
				});
				this.jPanelPlugins.add(button);
			}
		}
	}

	private void initSelf() {
		this.setTitle("JTalk");
		this.setIconImage(new ImageIcon(classLoader.getResource("com/jtalker/rs/icons/jtalker.png")).getImage());
		this.setSize(310, 245);
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				exitForm(e);
			}
		});
		this.setVisible(true);
	}

	/**
	 * 初始化中间聊天列表.
	 */
	private void initPaneMemberList() {
		jPanelMemberList = new JPanel();
		jPanelMemberList.setLayout(new GridLayout());
		jScrollPaneMembers = new JScrollPane();
		jListMembers = new JList(this.theClient.memberList);
		jListMembers.setCellRenderer(new MyCellRender(this));
		MouseListener mouseListener = new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					showChatWindow(null);
				}
			}

			@Override
			public void mousePressed(MouseEvent e) {
				maybeShowPopup(e);
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				maybeShowPopup(e);
			}

		};
		jListMembers.addMouseListener(mouseListener);
		// jListMembers.add
		jScrollPaneMembers.setViewportView(jListMembers);
		jPanelMemberList.add(jScrollPaneMembers);
		this.getContentPane().add(jPanelMemberList, BorderLayout.CENTER);
	}

	private void initToolBarSide() {
		jPanelToolBarSide = new JPanel();
		jPanelToolBarSide.setLayout(new BorderLayout());

		jToolBarSide = new JToolBar();
		jToolBarSide.setOrientation(SwingConstants.VERTICAL);
		jToolBarSide.setRollover(true);

		jButtonOpenChat = new JButton();
		jButtonOpenChat.setIcon(new ImageIcon(classLoader.getResource("com/jtalker/rs/icons/message_window.png")));
		jButtonOpenChat.setToolTipText("Open a chat window");
		jButtonOpenChat.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				showChatWindow(e);
			}
		});
		jButtonOpenChat.setMargin(new Insets(1, 2, 1, 2));
		jToolBarSide.add(jButtonOpenChat);

		jButtonSendMail = new JButton();
		jButtonSendMail.setIcon(new ImageIcon(classLoader.getResource("com/jtalker/rs/icons/send_mail.png")));
		jButtonSendMail.setToolTipText("Send a mail to selected users");
		jButtonSendMail.setMargin(new Insets(1, 2, 1, 2));
		jToolBarSide.add(jButtonSendMail);

		jPanelToolBarSide.add(jToolBarSide);
		this.getContentPane().add(jPanelToolBarSide, BorderLayout.EAST);
	}

	/**
	 * 初始化底部状态栏
	 */
	private void initBottomStatus() {
		jPanelStatus = new JPanel();
		jPanelStatus.setLayout(new BorderLayout());

		jLabelStatusVersion = new JLabel();
		jLabelStatusVersion.setBorder(new BevelBorder(BevelBorder.LOWERED));
		jLabelStatusVersion.setText("0.1");
		jPanelStatus.add(jLabelStatusVersion, BorderLayout.CENTER);

		jLabelStatusConnect = new JLabel();
		jLabelStatusConnect.setText("Ready");
		jLabelStatusConnect.setBorder(new BevelBorder(BevelBorder.LOWERED));
		jPanelStatus.add(jLabelStatusConnect, BorderLayout.EAST);

		this.getContentPane().add(jPanelStatus, BorderLayout.SOUTH);
	}

	/**
	 * 初始化工具栏.
	 */
	private void initToolBar() {
		jPanelTool = new JPanel();
		jPanelTool.setLayout(new BorderLayout());

		jToolBar = new JToolBar();
		jToolBar.setRollover(true);

		jButtonConnect = new JButton();
		jButtonConnect.setToolTipText("Connect/Disconnect");
		jButtonConnect.setIcon(new ImageIcon(classLoader.getResource("com/jtalker/rs/icons/connected.png")));
		jButtonConnect.setMargin(new Insets(1, 2, 1, 2));
		jButtonConnect.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				connectServer(e);
			}
		});
		jToolBar.add(jButtonConnect);

		jToggleButtonStatus = new JToggleButton();
		jToggleButtonStatus.setIcon(new ImageIcon(classLoader.getResource("com/jtalker/rs/icons/go_busy.png")));
		jToggleButtonStatus.setMargin(new Insets(1, 2, 1, 2));
		jToggleButtonStatus.setToolTipText("Set status to busy");
		jToggleButtonStatus.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (jMenuItemStatus.isSelected()) {
					jMenuItemStatus.setSelected(false);
				} else {
					jMenuItemStatus.setSelected(true);
				}
				setUserStatus();
			}
		});
		jToolBar.add(jToggleButtonStatus);

		jButtonConfig = new JButton();
		jButtonConfig.setIcon(new ImageIcon(classLoader.getResource("com/jtalker/rs/icons/configure.png")));
		jButtonConfig.setMargin(new Insets(1, 2, 1, 2));
		jButtonConfig.setToolTipText("Config JTalk");
		jButtonConfig.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				showSettings();
			}
		});
		jToolBar.add(jButtonConfig);
		jToolBar.addSeparator();

		jPanelPlugins = new JPanel();
		jPanelPlugins.setLayout(new GridLayout());
		jToolBar.add(jPanelPlugins);

		jPanelTool.add(jToolBar, BorderLayout.CENTER);
		this.getContentPane().add(jPanelTool, BorderLayout.NORTH);
	}

	/**
	 * 初始化菜单.
	 */
	private void initMenu() {
		jMenuBarMain = new JMenuBar();
		jMenuFile = new JMenu();
		jMenuFile.setText("File");
		jMenuItemSettings = new JMenuItem();
		jMenuItemSettings.setText("Settings...");
		jMenuItemSettings.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				showSettings();
			}
		});
		jMenuItemExit = new JMenuItem();
		jMenuItemExit.setText("Exit");
		jMenuItemExit.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				exitForm(null);
			}
		});
		jMenuFile.add(jMenuItemSettings);
		jMenuFile.add(jMenuItemExit);
		jMenuBarMain.add(jMenuFile);

		jMenuServer = new JMenu();
		jMenuServer.setText("Server");
		jMenuItemCreateAccount = new JMenuItem();
		jMenuItemCreateAccount.setText("Create Account...");
		jMenuItemCreateAccount.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				createAccount(e);
			}
		});
		jMenuServer.add(jMenuItemCreateAccount);
		jMenuItemCommand = new JMenuItem();
		jMenuItemCommand.setText("Send Command...");
		jMenuItemCommand.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				sendCommand();
			}
		});
		jMenuServer.add(jMenuItemCommand);
		jMenuItemCreateChatRoom = new JMenuItem();
		jMenuItemCreateChatRoom.setText("Create Chatroom");
		jMenuItemCreateChatRoom.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				createChatRoom(e);
			}
		});
		jMenuServer.add(jMenuItemCreateChatRoom);
		jMenuItemConnect = new JMenuItem();
		jMenuItemConnect.setText("Connect/Disconnect");
		jMenuItemConnect.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				connectServer(e);
			}
		});
		jMenuServer.add(jMenuItemConnect);
		jMenuBarMain.add(jMenuServer);

		jMenuStatus = new JMenu();
		jMenuStatus.setText("Status");
		jMenuItemStatus = new JCheckBoxMenuItem();
		jMenuItemStatus.setText("Busy");
		jMenuItemStatus.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (jToggleButtonStatus.isSelected()) {
					jToggleButtonStatus.setSelected(false);
				} else {
					jToggleButtonStatus.setSelected(true);
				}
				setUserStatus();
			}
		});
		jMenuStatus.add(jMenuItemStatus);
		jMenuBarMain.add(jMenuStatus);

		jMenuPlugins = new JMenu();
		jMenuPlugins.setText("Plugins");
		jMenuBarMain.add(jMenuPlugins);

		jMenuHelp = new JMenu();
		jMenuHelp.setText("?");
		jMenuItemAbout = new JMenuItem();
		jMenuItemAbout.setText("About");
		jMenuItemAbout.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				showAboutInfo(e);
			}
		});
		jMenuHelp.add(jMenuItemAbout);
		jMenuBarMain.add(jMenuHelp);

		this.setJMenuBar(jMenuBarMain);
	}

	/** Exit the Application */
	private void exitForm(WindowEvent evt) {// GEN-FIRST:event_exitForm
		System.exit(0);
	}

	/** Creates a new Account on the server */
	private void createAccount(ActionEvent evt) {
		new JTalkAccountCreater(this, true).setVisible(true);
		// new CreateAccountWindow(this, true).setVisible(true);
	}

	/**
	 * 
	 * @param i
	 */
	private void createChatRoom(ActionEvent event) {
		// TODO Auto-generated method stub
		// JOptionPane.showMessageDialog(null, "Create ChatRoom");
		new JTalkChatRoomCreater(this, true).setVisible(true);
	}

	/**
	 * Show about menu information.
	 * 
	 * @param e
	 */
	private void showAboutInfo(ActionEvent e) {
		// TODO Auto-generated method stub
		JOptionPane.showMessageDialog(null, "JTalker Version-0.1"
				+ "\nCopyright (C) 2009 by ChrM (http://www.chrm.info)\n\nThis program is free software; "
				+ "you can redistribute it and/or\nmodify it under the terms of the GNU General Public License "
				+ "as\npublished by the Free Software Foundation; either version 2 of\nthe License, or (at your "
				+ "option) any later version.\nThis program is distributed in the hope that it will be useful,"
				+ "\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS "
				+ "FOR A PARTICULAR PURPOSE. See the GNU\nGeneral Public License for more details.", "About JTalker",
				JOptionPane.INFORMATION_MESSAGE);
	}

	/**
	 * 连接服务器.
	 * 
	 * @param e
	 */
	public void connectServer(ActionEvent e) {
		if (!this.isConnected) { // 若未连接上则连接.
			if (this.theClient.connect()) {
				if(!this.theClient.savePassword){
					String retVal = JOptionPane.showInputDialog("Input password for \"" + this.theClient.userName
							+ "\"");
					if (retVal != null) {
						this.theClient.password = retVal;
					} else {
						this.theClient.closeConnection();
						return;
					}
				}
				this.theClient.loginOnServer();
			} else {
				this.isConnected = false;
				this.jLabelStatusConnect.setText("Cann't connect to " + this.theClient.getServerInfo());
				this.jButtonConnect
						.setIcon(new ImageIcon(classLoader.getResource("com/jtalker/rs/icons/connected.png")));
			}
		} else { // 若已连接上则断开.
			this.theClient.closeConnection();
			this.jLabelStatusConnect.setText("You are disconnected now.");
			this.jLabelStatusConnect.setIcon(null);
			this.isConnected = false;
			this.jButtonConnect.setIcon(new ImageIcon(classLoader.getResource("com/jtalker/rs/icons/connected.png")));
		}
	}

	/**
	 * 显示聊天窗口
	 * 
	 * @param e
	 */
	private void showChatWindow(ActionEvent e) {
		// TODO Auto-generated method stub
		MemberData m = this.getSelectedUser();
		if (m != null) {
			m.showChatWindow(this);
		}
	}

	/**
	 * Show pop-up for user.
	 * 
	 * @param e
	 */
	private void maybeShowPopup(MouseEvent e) {
		if (this.userPopup == null) {
			this.userPopup = new JTalkFrontPopup(this);
		}
		if (e.isPopupTrigger()) {
			if (this.jListMembers.getFirstVisibleIndex() == -1) {
				return;
			}
			this.jListMembers.setSelectedIndex(this.jListMembers.locationToIndex(e.getPoint()));
			this.userPopup.show(e.getComponent(), e.getX(), e.getY());
		}
	}

	/**
	 * 获取选中的用户
	 * 
	 * @return
	 */
	public MemberData getSelectedUser() {
		// TODO Auto-generated method stub
		int index = this.jListMembers.getSelectedIndex();
		if (index == -1) {
			return null;
		}
		return this.theClient.allMembers.get(index);
	}

	/**
	 * 当有新用户登录时,刷新用户列表.
	 */
	public void refreshActionPerformed() {
		if (this.theClient.state == JTalkClient.STATE_OFFLINE) {
			this.connectionEstablished(false);
		} else if (this.theClient.state == JTalkClient.STATE_CONNECTED) {
			this.connectionEstablished(true);
		}
		if (this.isConnected) {
			this.theClient.memberList.propertyChanged();
		}
	}

	/**
	 * 设置客户端的登录状态.
	 * 
	 * @param b
	 */
	private void connectionEstablished(boolean yes) {
		if (yes) {
			this.isConnected = true;
			this.jLabelStatusConnect.setText("Conntected to" + this.theClient.getServerInfo());
			this.jButtonConnect
					.setIcon(new ImageIcon(classLoader.getResource("com/jtalker/rs/icons/disconnected.png")));
		} else {
			this.isConnected = false;
			this.jLabelStatusConnect.setText("Can't log in on server!");
		}
	}

	public class UpdateTimer extends Thread {

		private JTalkClientFront parent = null;

		public UpdateTimer(JTalkClientFront parent) {
			this.parent = parent;
			this.setName("Client-UpdateTimer-" + this.toString());
		}

		@Override
		public void run() {
			while (true) {
				try {
					this.parent.refreshActionPerformed();
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

	/**
	 * 插件菜单类.
	 * 
	 * @author Administrator
	 * 
	 */
	public class PlugInMenuItem extends JMenuItem {

		private static final long serialVersionUID = 1L;
		private String pluginClass = null;
		private int type = 0; // 0: mainGui, 1: Settings

		public PlugInMenuItem(String pluginClass, int type) {
			super();
			this.pluginClass = pluginClass;
			this.type = type;
		}
	}

	public class MyCellRender extends JLabel implements ListCellRenderer {

		private JTalkClientFront parent = null;
		private ImageIcon userIcon = new ImageIcon(classLoader.getResource("com/jtalker/rs/icons/user.png"));
		private ImageIcon userMeIcon = new ImageIcon(classLoader.getResource("com/jtalker/rs/icons/me.png"));
		private ImageIcon userbIcon = new ImageIcon(classLoader.getResource("com/jtalker/rs/icons/user_busy.png"));
		private ImageIcon chatroomIcon = new ImageIcon(classLoader.getResource("com/jtalker/rs/icons/chatroom.png"));
		private ImageIcon newMailIcon = new ImageIcon(classLoader.getResource("com/jtalker/rs/icons/new_mail.png"));

		public MyCellRender(JTalkClientFront parent) {
			this.parent = parent;
		}

		@Override
		public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
				boolean cellHasFocus) {
			if (value == null) {
				return null;
			}
			MemberData member = (MemberData) value;
			String name = member.name;
			this.setText(name.replaceAll(" AT ", " @ "));
			if (member.hasNewMessage) {
				if (!member.short_name.equals(this.parent.theClient.userName)) {
					this.setIcon(newMailIcon);
					if (!member.chatWindowOpened()) {
						this.parent.notifyOnNewMessage(true, name);
					}
				} else {
					this.setIcon(userMeIcon);
				}
			} else if ("busy".equals(member.status)) {
				this.setIcon(userbIcon);
			} else if (JTalkParser.USER_TYPE_CHATROOM.equals(member.type)) {
				this.setIcon(chatroomIcon);
			} else {
				this.parent.notifyOnNewMessage(false, null);
				if (member.short_name.equals(this.parent.theClient.userName)) {
					this.setIcon(userMeIcon);
				} else {
					this.setIcon(userIcon);
				}
			}
			if (isSelected) {
				this.setBackground(list.getSelectionBackground());
				this.setForeground(list.getSelectionForeground());
			} else {
				this.setBackground(list.getBackground());
				this.setForeground(list.getForeground());
			}

			this.setEnabled(list.isEnabled());
			this.setFont(list.getFont());
			this.setOpaque(true);

			if (!member.isConnected()) {
				this.setEnabled(false);
			}

			return this;
		}

	}

	/**
	 * 打开聊天窗口.
	 */
	public void openChatWindow() {
		this.showChatWindow(null);
	}

	/**
	 * 提示有新消息.
	 * 
	 * @param enabled
	 * @param name
	 */
	public void notifyOnNewMessage(boolean enabled, String name) {
		if (enabled) {
			switch (this.theClient.newMailNotificationType) {
			case 0:
				break;
			case 1:
				this.toFront();
				break;
			case 2:
				if (this.newMessageNotificator == null) {
					this.newMessageNotificator = new NotificationWindow(this);
					this.newMessageNotificator.setPosition(NotificationWindow.BOTTOM_RIGHT);
				}
				this.newMessageNotificator.setMemberName(name);
				this.newMessageNotificator.setVisible(true);
				break;
			case 3:
				Toolkit.getDefaultToolkit().beep();
			}
		} else {
			if (this.newMessageNotificator != null) {
				this.newMessageNotificator.setVisible(false);
			}
		}
	}

	/**
	 * 向服务器端发送命令.
	 */
	private void sendCommand() {
		// TODO Auto-generated method stub
		if (this.myCommandDialog == null) {
			this.myCommandDialog = new JTalkFrontCommand(this);
		}
		this.myCommandDialog.setVisible(true);
	}

	/**
	 * 删除聊天室.
	 * 
	 * @param roomName
	 *            聊天室名称
	 */
	public void removeChatroom(String roomName) {
		if (!this.theClient.isConnected) {
			return;
		}
		this.theClient.sendMessage("std::removeChatRoom(\"" + roomName + "\")", null, "command", null, "rmchat01");
	}

	/**
	 * 向聊天室增加一个成员.
	 * 
	 * @param roomName
	 *            聊天室名称
	 * @param userName
	 *            要删除的聊天室成员名称
	 */
	public void addChatroomUser(String roomName, String userName) {
		if (!this.theClient.isConnected) {
			return;
		}
		this.theClient.sendMessage("std::addChatRoomUser(\"" + roomName + "\", \"" + userName + "\")", null, "command",
				null, "addchatuser01");
	}

	/**
	 * 从聊天室中删除一个成员.
	 * 
	 * @param roomName
	 *            聊天室名称
	 * @param userName
	 *            要删除的聊天室成员名称
	 */
	public void removeChatroomUser(String roomName, String userName) {
		if (!this.theClient.isConnected) {
			return;
		}
		this.theClient.sendMessage("std::removeChatRoomUser(\"" + roomName + "\", \"" + userName + ")", null,
				"command", null, "rmchatuser01");
	}

	/**
	 * 设置用户状态.
	 */
	private void setUserStatus() {
		// TODO Auto-generated method stub
		if (this.jToggleButtonStatus.isSelected()) {
			this.theClient.userStatus = "Busy";
		} else {
			this.theClient.userStatus = "normal";
		}
		if (this.isConnected) {
			this.theClient.lookUp();
			this.theClient.memberList.propertyChanged();
		}
	}

	/**
	 * 显示设置面板.
	 */
	private void showSettings() {
		if (this.mySettings == null) {
			this.mySettings = new JTalkFrontSettings(this);
		}
		this.mySettings.setVisible(true);
	}

	/**
	 * 加载所有插件.
	 * 
	 * @return
	 */
	public boolean loadAllPlugins() {
		this.jMenuPlugins.removeAll();

		if (this.myPluginsLoader == null) {
			System.out.println("[PLUGIN]: Loader not exists now - create object");
			this.myPluginsLoader = new JTalkPlugInLoader(this);
		}
		System.out.println("[PLUGIN]: Reload all plugins");
		if (!this.myPluginsLoader.initPlugins(this.theClient.pluginDir)) {
			return false;
		}

		String[] plugins = this.myPluginsLoader.getPluginClassNames();
		if (plugins != null) {
			for (int i = 0; i < plugins.length; i++) {
				this.createPluginMenuFor(plugins[i]);
			}
		}
		// OK, all Plugins added, create Overview MenuItem
		this.jMenuPlugins.addSeparator();
		PlugInMenuItem menuItem = new PlugInMenuItem("Overview", 2);
		menuItem.setText("Plugin Overview...");
		menuItem.addActionListener(this);
		this.jMenuPlugins.add(menuItem);
		return true;
	}

	/**
	 * 创建插件菜单.
	 * 
	 * @param className
	 *            插件类名
	 */
	private void createPluginMenuFor(String className) {
		JMenu pluginMenu = new JMenu();
		pluginMenu.setText(this.myPluginsLoader.getPluginByClassName(className).getName());
		PlugInMenuItem pluginMenuItem = new PlugInMenuItem(className, 0);
		pluginMenuItem.setText("Open Dialog...");
		pluginMenuItem.addActionListener(this);
		pluginMenu.add(pluginMenuItem);
		PlugInMenuItem settingsMenuItem = new PlugInMenuItem(className, 1);
		settingsMenuItem.setText("Plugin Settings...");
		settingsMenuItem.addActionListener(this);
		pluginMenu.add(settingsMenuItem);

		this.jMenuPlugins.add(pluginMenu);

	}

	/**
	 * 获取插件加载器.
	 * 
	 * @return
	 */
	public JTalkPlugInLoader getPluginLoader() {
		return this.myPluginsLoader;
	}

	/**
	 * 显示插件.
	 * 
	 * @param e
	 */
	private void openPluginMainGUIFor(String plugin) {
		System.out.println("main: " + plugin);
		this.myPluginsLoader.showPluginsGUI(plugin, 0);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		PlugInMenuItem menuItem = (PlugInMenuItem) e.getSource();
		if (menuItem.type == 0) {
			this.openPluginMainGUIFor(menuItem.pluginClass);
		} else if (menuItem.type == 1) {
			this.openPluginSettingsGUIFor(menuItem.pluginClass);
		} else if (menuItem.type == 2) {
			if (this.myPluginsInfo == null) {
				this.myPluginsInfo = new JTalkClientPluginsInfo(this);
			}
			if (this.myPluginsInfo.updatePluginList(null)) {
				this.myPluginsInfo.setVisible(true);
			}
		}
	}

	/**
	 * 打开插件设置面板.
	 * 
	 * @param pluginClass
	 */
	private void openPluginSettingsGUIFor(String pluginClass) {
		// TODO Auto-generated method stub
		this.myPluginsLoader.showPluginsGUI(pluginClass, 0);
	}

	@Override
	public boolean setCommandAnswer(String messageID, String sender, String content) {
		if ("disconnect01".equals(messageID)) {
			this.jLabelStatusConnect.setText("You are disconnected now.");
			this.jLabelStatusConnect.setIcon(null);
			this.isConnected = false;
			this.jButtonConnect.setIcon(new ImageIcon(classLoader.getResource("com/jtalker/rs/icons/connected.png")));
		}
		return false;
	}
	
	public static void main(String args[]) {
		EventQueue.invokeLater(new Runnable() {

			@Override
			public void run() {
				JTalkClient client = new JTalkClient();
				// Set Look and Feel
				try {
					UIManager.setLookAndFeel(client.guiPlaf);
				} catch (Exception e) {
					System.err.println("*** Can't set Look'n'Feel. Use default.");
				}
				new JTalkClientFront(client).setVisible(true);
			}
			
		});
	}

}
